package com.qianniu.napi.common.util;

//import com.sun.image.codec.jpeg.JPEGCodec;
//import com.sun.image.codec.jpeg.JPEGEncodeParam;
//import com.sun.image.codec.jpeg.JPEGImageEncoder;

import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Positions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import javax.net.ssl.HttpsURLConnection;
import java.awt.*;
import java.awt.color.ColorSpace;
import java.awt.geom.Ellipse2D;
import java.awt.image.BufferedImage;
import java.awt.image.ColorConvertOp;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Random;

public class ImageUtil {


    private static final Logger logger = LoggerFactory.getLogger(ImageUtil.class);

    /**
     * 按指定高度 等比例缩放图片
     *
     * @param imageFile
     * @param newWidth  新图的宽度
     * @throws IOException
     */
    public static BufferedImage scaleImageByWidth(File imageFile, int newWidth) throws IOException {
        if (!imageFile.canRead())
            return null;
        BufferedImage bufferedImage = ImageIO.read(imageFile);
        if (null == bufferedImage)
            return null;

        int originalWidth = bufferedImage.getWidth(null);
        int originalHeight = bufferedImage.getHeight(null);
        double scale = (double) originalWidth / (double) newWidth;    // 缩放的比例
        int newHeight = (int) (originalHeight / scale);

        return zoomImageUtils(imageFile, bufferedImage, newWidth, newHeight);
    }

    /**
     * 按指定高度 等比例缩放图片
     *
     * @param imageFile
     * @param newHeight 新图的高度
     * @throws IOException
     */
    public static BufferedImage scaleImageByHeight(File imageFile, int newHeight) throws IOException {
        if (!imageFile.canRead())
            return null;
        BufferedImage bufferedImage = ImageIO.read(imageFile);
        if (null == bufferedImage)
            return null;

        int originalWidth = bufferedImage.getWidth(null);
        int originalHeight = bufferedImage.getHeight(null);

        double scale = (double) originalHeight / (double) newHeight;    // 缩放的比例
        int newWidth = (int) (originalWidth / scale);

        return zoomImageUtils(imageFile, bufferedImage, newWidth, newHeight);
    }

    private static BufferedImage zoomImageUtils(File imageFile, BufferedImage bufferedImage,
                                                int width, int height)
            throws IOException {

        String imageType = imageFile.getName().substring(imageFile.getName().lastIndexOf(".") + 1);

        // 处理 png 背景变黑的问题
        if (imageType != null && (imageType.trim().toLowerCase().endsWith("png") || imageType.trim().toLowerCase().endsWith("gif"))) {
            BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2d = bi.createGraphics();
            bi = g2d.getDeviceConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT);
            g2d.dispose();

            g2d = bi.createGraphics();
            Image from = bufferedImage.getScaledInstance(width, height, Image.SCALE_AREA_AVERAGING);
            g2d.drawImage(from, 0, 0, null);
            g2d.dispose();
            return bi;
//            ImageIO.write(bi, imageType, new File(newPath));
        } else {
            // 高质量压缩，其实对清晰度而言没有太多的帮助
//            BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//            tag.getGraphics().drawImage(bufferedImage, 0, 0, width, height, null);
//
//            FileOutputStream out = new FileOutputStream(newPath);    // 将图片写入 newPath
//            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
//            JPEGEncodeParam jep = JPEGCodec.getDefaultJPEGEncodeParam(tag);
//            jep.setQuality(1f, true);    //压缩质量, 1 是最高值
//            encoder.encode(tag, jep);
//            out.close();

            BufferedImage newImage = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR);
            Graphics g = newImage.getGraphics();
            g.drawImage(bufferedImage, 0, 0, width, height, null);
            g.dispose();
            return newImage;
//            ImageIO.write(newImage, imageType, new File(newPath));
        }
    }

    /**
     * 获取随机颜色
     *
     * @return
     */
    public static Color getRandomColor() {
        Random random = new Random();
        int r = random.nextInt(255);
        int g = random.nextInt(255);
        int b = random.nextInt(255);
        return new Color(r, g, b);
    }

    public BufferedImage getGrayPicture(BufferedImage originalImage) {
        BufferedImage grayPicture;
        int imageWidth = originalImage.getWidth();
        int imageHeight = originalImage.getHeight();

        grayPicture = new BufferedImage(imageWidth, imageHeight,
                BufferedImage.TYPE_3BYTE_BGR);
        ColorConvertOp cco = new ColorConvertOp(ColorSpace
                .getInstance(ColorSpace.CS_GRAY), null);
        cco.filter(originalImage, grayPicture);
        return grayPicture;
    }

    public BufferedImage getGrayPictureByRGB(BufferedImage originalImage) {
        int green = 0, red = 0, blue = 0, rgb;
        int imageWidth = originalImage.getWidth();
        int imageHeight = originalImage.getHeight();
        for (int i = originalImage.getMinX(); i < imageWidth; i++) {
            for (int j = originalImage.getMinY(); j < imageHeight; j++) {
//图片的像素点其实是个矩阵，这里利用两个for循环来对每个像素进行操作
                Object data = originalImage.getRaster().getDataElements(i, j, null);//获取该点像素，并以object类型表示
                red = originalImage.getColorModel().getRed(data);
                blue = originalImage.getColorModel().getBlue(data);
                green = originalImage.getColorModel().getGreen(data);
                red = (red * 3 + green * 6 + blue * 1) / 10;
                green = red;
                blue = green;
/*
这里将r、g、b再转化为rgb值，因为bufferedImage没有提供设置单个颜色的方法，只能设置rgb。
rgb最大为8388608，当大于这个值时，应减去255*255*255即16777216
*/
                rgb = (red * 256 + green) * 256 + blue;
                if (rgb > 8388608) {
                    rgb = rgb - 16777216;
                }
                //将rgb值写回图片
                originalImage.setRGB(i, j, rgb);
            }

        }

        return originalImage;
    }

    /**
     * 传入的图像必须是正方形的 才会 圆形  如果是长方形的比例则会变成椭圆的
     *
     * @param origin 用户头像地址
     * @return
     * @throws IOException
     */
    public static BufferedImage convertCircular(BufferedImage origin) throws IOException {

//        BufferedImage bi1 = ImageIO.read(new File(url));
//        //这种是黑色底的
//        BufferedImage bi2 = new BufferedImage(bi1.getWidth(), bi1.getHeight(), BufferedImage.TYPE_INT_RGB);

        //透明底的图片
        BufferedImage bi2 = new BufferedImage(origin.getWidth(), origin.getHeight(), BufferedImage.TYPE_4BYTE_ABGR);
        Ellipse2D.Double shape = new Ellipse2D.Double(0, 0, origin.getWidth(), origin.getHeight());
        Graphics2D g2 = bi2.createGraphics();
        g2.setClip(shape);
        // 使用 setRenderingHint 设置抗锯齿
//        RenderingHints renderingHint = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2.drawImage(origin, 0, 0, null);
        //设置颜色
        g2.setBackground(Color.green);
        g2.dispose();
        return bi2;
    }

    /**
     * 通过网络获取图片
     *
     * @param url
     * @return
     */
    public static BufferedImage getUrlByBufferedImage(String url) {
        try {
            URL urlObj = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection();
            // 连接超时
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setConnectTimeout(25000);
            // 读取超时 --服务器响应比较慢,增大时间
            conn.setReadTimeout(25000);
            conn.setRequestMethod("GET");
            conn.addRequestProperty("Accept-Language", "zh-cn");
            conn.addRequestProperty("Content-type", "image/jpeg");
            conn.addRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727)");
            conn.connect();
            BufferedImage bufImg = ImageIO.read(conn.getInputStream());
            conn.disconnect();
            return bufImg;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }


    /**
     * 缩小Image，此方法返回源图像按给定宽度、高度限制下缩放后的图像
     *
     * @param inputImage
     * @param newWidth：压缩后宽度
     * @param newHeight：压缩后高度
     * @throws java.io.IOException return
     */
    public static BufferedImage scaleByPercentage(BufferedImage inputImage, int newWidth, int newHeight) throws Exception {
        //获取原始图像透明度类型
        int type = inputImage.getColorModel().getTransparency();
        int width = inputImage.getWidth();
        int height = inputImage.getHeight();

        //开启抗锯齿
        RenderingHints renderingHints = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        //使用高质量压缩
        renderingHints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        BufferedImage img = new BufferedImage(newWidth, newHeight, type);
        Graphics2D graphics2d = img.createGraphics();
        graphics2d.setRenderingHints(renderingHints);
        graphics2d.drawImage(inputImage, 0, 0, newWidth, newHeight, 0, 0, width, height, null);
        graphics2d.dispose();
        return img;
    }

    /**
     * 创建图片缩略图(等比缩放 无失真缩放)
     *
     * @param src    源图片文件完整路径
     * @param dist   目标图片文件完整路径
     * @param width  缩放的宽度
     * @param height 缩放的高度
     * @param flag   true 按照实际长宽输出  如果false按照比例进行无失真压缩
     */
//    public static boolean createThumb(String src, String dist, float width, float height, boolean flag) {
//        boolean flag1 = false;
//        try {
//            File srcfile = new File(src);
//            if (!srcfile.exists()) {
//                System.out.println("文件不存在");
//                return flag1;
//            }
//            BufferedImage image = ImageIO.read(srcfile);
//
//            // 获得缩放的比例
//
//            double ratio = 1.0;
//            // 判断如果高、宽都不大于设定值，则不处理
//            if (image.getHeight() > height || image.getWidth() > width) {
//                if (image.getHeight() > image.getWidth()) {
//                    ratio = height / image.getHeight();
//                } else {
//                    ratio = width / image.getWidth();
//                }
//            }
//            int newWidth = flag ? (int) width : (int) (image.getWidth() * ratio);
//            int newHeight = flag ? (int) height : (int) (image.getHeight() * ratio);
//            BufferedImage bfImage = new BufferedImage(newWidth, newHeight,
//                    BufferedImage.TYPE_INT_RGB);
//            flag1 = bfImage.getGraphics().drawImage(
//                    image.getScaledInstance(newWidth, newHeight,
//                            Image.SCALE_SMOOTH), 0, 0, null);
//
//            FileOutputStream os = new FileOutputStream(dist);
//            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(os);
//            JPEGEncodeParam jParam = encoder.getDefaultJPEGEncodeParam(bfImage);
//            jParam.setQuality(1f, false);
//            encoder.encode(bfImage);
//            os.close();
//            flag1 = true;
//        } catch (Exception e) {
//            flag1 = false;
//        }
//        return flag1;
//    }


    /**
     * 给图片添加图片水印
     *
     * @param pressImg      水印图片
     * @param srcImageFile  源图像地址
     * @param destImageFile 目标图像地址
     * @param x             修正值。 默认在中间
     * @param y             修正值。 默认在中间
     * @param alpha         透明度：alpha 必须是范围 [0.0, 1.0] 之内（包含边界值）的一个浮点数字
     */
    public final static void pressImage(String pressImg, String srcImageFile, String destImageFile,
                                        int x, int y, float alpha) {
        try {
            File img = new File(srcImageFile);
            Image src = ImageIO.read(img);
            int wideth = src.getWidth(null);
            int height = src.getHeight(null);
            BufferedImage image = new BufferedImage(wideth, height,
                    BufferedImage.TYPE_INT_RGB);
            Graphics2D g = image.createGraphics();
            g.drawImage(src, 0, 0, wideth, height, null);
            // 水印文件
            Image src_biao = ImageIO.read(new File(pressImg));
            int wideth_biao = src_biao.getWidth(null);
            int height_biao = src_biao.getHeight(null);
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));

            g.drawImage(src_biao, (wideth - wideth_biao) / 2,
                    (height - height_biao) / 2, wideth_biao, height_biao, null);
            // 水印文件结束
            g.dispose();
            ImageIO.write((BufferedImage) image, "JPG", new File(destImageFile));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 给图片添加文字水印
     *
     * @param pressText     水印文字
     * @param srcImageFile  源图像地址
     * @param destImageFile 目标图像地址
     * @param fontName      水印的字体名称
     * @param fontStyle     水印的字体样式
     * @param color         水印的字体颜色
     * @param fontSize      水印的字体大小
     * @param x             修正值
     * @param y             修正值
     * @param alpha         透明度：alpha 必须是范围 [0.0, 1.0] 之内（包含边界值）的一个浮点数字
     */
    public final static void pressText(String pressText,
                                       String srcImageFile, String destImageFile, String fontName,
                                       int fontStyle, Color color, int fontSize, int x,
                                       int y, float alpha) {
        try {
            File img = new File(srcImageFile);
            Image src = ImageIO.read(img);
            int width = src.getWidth(null);
            int height = src.getHeight(null);
            BufferedImage image = new BufferedImage(width, height,
                    BufferedImage.TYPE_INT_RGB);
            Graphics2D g = image.createGraphics();
            g.drawImage(src, 0, 0, width, height, null);
            g.setColor(color);
            g.setFont(new Font(fontName, fontStyle, fontSize));
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,
                    alpha));
            // 在指定坐标绘制水印文字
            g.drawString(pressText, (width - (getLength(pressText) * fontSize))
                    / 2 + x, (height - fontSize) / 2 + y);
            g.dispose();
            ImageIO.write((BufferedImage) image, "JPEG", new File(destImageFile));// 输出到文件流
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 给图片添加文字水印
     *
     * @param pressText     水印文字
     * @param srcImageFile  源图像地址
     * @param destImageFile 目标图像地址
     * @param fontName      字体名称
     * @param fontStyle     字体样式
     * @param color         字体颜色
     * @param fontSize      字体大小
     * @param x             修正值
     * @param y             修正值
     * @param alpha         透明度：alpha 必须是范围 [0.0, 1.0] 之内（包含边界值）的一个浮点数字
     */
    public final static void pressText2(String pressText, String srcImageFile, String destImageFile,
                                        String fontName, int fontStyle, Color color, int fontSize, int x,
                                        int y, float alpha) {
        try {
            File img = new File(srcImageFile);
            Image src = ImageIO.read(img);
            int width = src.getWidth(null);
            int height = src.getHeight(null);
            BufferedImage image = new BufferedImage(width, height,
                    BufferedImage.TYPE_INT_RGB);
            Graphics2D g = image.createGraphics();
            g.drawImage(src, 0, 0, width, height, null);
            g.setColor(color);
            g.setFont(new Font(fontName, fontStyle, fontSize));
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,
                    alpha));
            // 在指定坐标绘制水印文字
            g.drawString(pressText, (width - (getLength(pressText) * fontSize))
                    / 2 + x, (height - fontSize) / 2 + y);
            g.dispose();
            ImageIO.write((BufferedImage) image, "JPEG", new File(destImageFile));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 彩色转为黑白
     *
     * @param srcImageFile  源图像地址
     * @param destImageFile 目标图像地址
     */
    public final static void gray(String srcImageFile, String destImageFile) {
        try {
            BufferedImage src = ImageIO.read(new File(srcImageFile));
            BufferedImage newPic = new BufferedImage(src.getWidth(), src.getHeight(),
                    BufferedImage.TYPE_3BYTE_BGR);
            ColorConvertOp cco = new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_sRGB), null);
            cco.filter(src, newPic);

            ImageIO.write(newPic, "JPEG", new File(destImageFile));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 计算text的长度（一个中文算两个字符）
     *
     * @param text
     * @return
     */
    public final static int getLength(String text) {
        int length = 0;
        for (int i = 0; i < text.length(); i++) {
            if (new String(text.charAt(i) + "").getBytes().length > 1) {
                length += 2;
            } else {
                length += 1;
            }
        }
        return length / 2;
    }

    public static void main(String[] args) {

//        String cxbqr = "/Users/chenxuebin/Downloads/tmp_img/tp/cxbqr.jpg";
////        String cxbqr = "/Users/chenxuebin/Downloads/tmp_img/tp/ad400.png";
//        String target = "/Users/chenxuebin/Downloads/tmp_img/tp/cxbqr_gray.png";
//        Color black = new Color (0,0,0);
////        Color fontcolor = new Color (82,179,192);//52b3c0
//        Color fontcolor = new Color (252,81,5);//fc

//        String src = "/Users/chenxuebin/Downloads/tmp_img/UI/qianbaihui.png";
//        String src = "/Users/chenxuebin/Downloads/tmp_img/UI/qianbaihui.png";
//        String src = "/Users/chenxuebin/Downloads/tmp_img/1503897514387.jpg";

//        String src = "/Users/chenxuebin/Downloads/tmp_img/UI/qianbaihui_new.jpg";
//        String target = "/Users/chenxuebin/Downloads/tmp_img/UI/qianbaihui_new2.jpg";

//        String src = "/Users/chenxuebin/Downloads/tmp_img/qianbaihui_new.jpg";
//        String target = "/Users/chenxuebin/Downloads/tmp_img/qianbaihui_new2.jpg";

        // === 2017-12-21
        String src = "/Users/chenxuebin/Downloads/tmp_img/zhufu_tuiguang.jpeg";
        String target = "/Users/chenxuebin/Downloads/tmp_img/zhufu_tuiguang_new.jpeg";

        java.util.List<Color> list = new ArrayList<Color>();

//        replaceImageColor(src,target,"e5fff3","ffffff");
//        replaceImageColor(src,target,"e1fffa","ffffff");
//        replaceImageColor(src,target,"edfff6","ffffff");

        list.add(ColorUtil.toColor("#edfff6"));
        list.add(ColorUtil.toColor("#000000"));
        list.add(ColorUtil.toColor("#d5fff3"));
        list.add(ColorUtil.toColor("#eefff7"));
        list.add(ColorUtil.toColor("#d4fff2"));
        list.add(ColorUtil.toColor("#e4fff2"));
        list.add(ColorUtil.toColor("#f1fffb"));
        list.add(ColorUtil.toColor("#e3fff3"));
        list.add(ColorUtil.toColor("#d6ebe2"));
        list.add(ColorUtil.toColor("#f0fffa"));
        list.add(ColorUtil.toColor("#deeeed"));

        list.add(ColorUtil.toColor("#e9faf2"));
        list.add(ColorUtil.toColor("#e7fbf0"));
        list.add(ColorUtil.toColor("#fcffff"));

        list.add(ColorUtil.toColor("#eafbf3"));
        list.add(ColorUtil.toColor("#f5fffa"));
        list.add(ColorUtil.toColor("#e4fef3"));

        list.add(ColorUtil.toColor("#e9fdf4"));
        list.add(ColorUtil.toColor("#ecfff7"));
        list.add(ColorUtil.toColor("#f2fffb"));

        list.add(ColorUtil.toColor("#f1fff9"));
        list.add(ColorUtil.toColor("#e4f9f2"));
        list.add(ColorUtil.toColor("#edf8f4"));

        list.add(ColorUtil.toColor("#eafcf0"));
        list.add(ColorUtil.toColor("#e8fcf1"));
        list.add(ColorUtil.toColor("#ecfff7"));

        list.add(ColorUtil.toColor("#f3fffb"));
        list.add(ColorUtil.toColor("#f0fffa"));
        list.add(ColorUtil.toColor("#fafefd"));
        list.add(ColorUtil.toColor("#f3f7f6"));

        list.add(ColorUtil.toColor("#eef9f5"));
        list.add(ColorUtil.toColor("#e7faf4"));
        list.add(ColorUtil.toColor("#e3f8f1"));

//        replaceImageColors(src,target,list,Color.white);
//        replaceImageColors(src, target, list, ColorUtil.toColor("#10afff"));
//        gray(cxbqr,target);

        String path = "/fafa/www/images/qiaqiaquanxining/store/tmp_a86b4636cc14.jpg";
        String imgbak = path.replace("/store/", "/storebak/");
        System.out.println(imgbak);


    }

//    private void pixelGrabber(intbuffer[]){
//        try{MediaTracker tracker=new MediaTracke(this);tracker.addImage(img,0);
//            tracker.waitForAll();
//            PixelGrabber grabber=new PixelGrabber(img,0,0,imgWidth,imgHeight,buffer,0,imgWidth);
//            try{grabber.grabPixels();}
//            catch(InterruptedException e){
//                e.printStackTrace();
//            }
//        }catch(Exception e){
//            e.printStackTrace();
//        }
//    }

    public static void replaceImageColor(String source, String target, String srcColor, String targetColor) {
        URL http;
        try {

            if (source.trim().startsWith("https")) {
                http = new URL(source);
                HttpsURLConnection conn = (HttpsURLConnection) http.openConnection();
                conn.setRequestMethod("GET");
            } else if (source.trim().startsWith("http")) {
                http = new URL(source);
                HttpURLConnection conn = (HttpURLConnection) http.openConnection();
                conn.setRequestMethod("GET");
            } else {
                http = new File(source).toURI().toURL();
            }
            BufferedImage bi = ImageIO.read(new File(source));

            int srcPixel = Integer.valueOf(srcColor.replace("#", ""), 16) - 16777216;
            int tarPixel = Integer.valueOf(targetColor.replace("#", ""), 16) - 16777216;
            System.out.println("srcPixel=" + srcPixel + " tarPixel=" + tarPixel);

            for (int i = 0; i < bi.getWidth(); i++) {
                for (int j = 0; j < bi.getHeight(); j++) {
                    if (srcPixel == bi.getRGB(i, j)) {
                        System.out.println("i=" + i + " j=" + j + " tarPixel=" + tarPixel);
                        bi.setRGB(i, j, tarPixel);
                    }
                }
            }

            ImageIO.write(bi, "JPEG", new File(target));
            bi.flush();
        } catch (IOException e) {

        }
    }

    public static void replaceImageColor(String source, String target, Color srcColor, Color targetColor) {
        URL http;
        try {

            if (source.trim().startsWith("https")) {
                http = new URL(source);
                HttpsURLConnection conn = (HttpsURLConnection) http.openConnection();
                conn.setRequestMethod("GET");
            } else if (source.trim().startsWith("http")) {
                http = new URL(source);
                HttpURLConnection conn = (HttpURLConnection) http.openConnection();
                conn.setRequestMethod("GET");
            } else {
                http = new File(source).toURI().toURL();
            }
            BufferedImage bi = ImageIO.read(new File(source));
//            BufferedImage bi = ImageIO.read(http.openStream());

            System.out.println("srcColor.getRGB()=" + srcColor.getRGB());
            System.out.println("targetColor.getRGB()=" + targetColor.getRGB());

            for (int i = 0; i < bi.getWidth(); i++) {
                for (int j = 0; j < bi.getHeight(); j++) {
//                    System.out.println(bi.getRGB(i, j));
                    if (srcColor.getRGB() == bi.getRGB(i, j)) {
//                        System.out.println(i + "," + j + "  from:" + srcColor.getRGB() + " to" + targetColor.getRGB());
                        bi.setRGB(i, j, targetColor.getRGB());
                    }
                }
            }

            ImageIO.write(bi, "JPEG", new File(target));
            bi.flush();
        } catch (IOException e) {

        }

    }

    public static void replaceImageColors(String source, String target, java.util.List<Color> srcColors, Color targetColor) {
        URL http;
        try {

            if (source.trim().startsWith("https")) {
                http = new URL(source);
                HttpsURLConnection conn = (HttpsURLConnection) http.openConnection();
                conn.setRequestMethod("GET");
            } else if (source.trim().startsWith("http")) {
                http = new URL(source);
                HttpURLConnection conn = (HttpURLConnection) http.openConnection();
                conn.setRequestMethod("GET");
            } else {
                http = new File(source).toURI().toURL();
            }
            BufferedImage bi = ImageIO.read(new File(source));

            for (int i = 0; i < bi.getWidth(); i++) {
                for (int j = 0; j < bi.getHeight(); j++) {

                    for (Color srcColor : srcColors) {
                        if (srcColor.getRGB() == bi.getRGB(i, j)) {
                            bi.setRGB(i, j, targetColor.getRGB());
                        }
                    }
                }
            }

            System.out.println("start to wirte image file");
            ImageIO.write(bi, "JPEG", new File(target));
            bi.flush();
        } catch (IOException e) {

        }
    }


    /*
     * srcFile 图片路径
	 * targetFile 图片路径
	 * srcColor 需要替换的颜色 如：000000(不带#)
	 * targetColor 替换后的颜色
	 * */
    public static void changeQrColor(String srcFile, String targetPath, Color srcColor, Color targetColor) {
        String base = "";
        File file = new File(srcFile);
        File targetFile = new File(targetPath);

        if (!file.exists()) {
            logger.debug("changeQrColor exit for srcFile not exist");
            return;
        }
        if (targetFile.exists()) {
            logger.debug("changeQrColor start to delete old file");
            targetFile.deleteOnExit();
            targetFile = new File(targetPath);
        }

        BufferedImage bi = null;
        BufferedImage bi1 = null;

        //
        int pixel0d = Integer.valueOf("0d0d0d", 16) - 16777216;
        int pixel16 = Integer.valueOf("161616", 16) - 16777216;
        int pixel1c = Integer.valueOf("1c1c1c", 16) - 16777216;
        int pixel22 = Integer.valueOf("222222", 16) - 16777216;
        int pixel2a = Integer.valueOf("2a2a2a", 16) - 16777216;
        int pixel26 = Integer.valueOf("262626", 16) - 16777216;
        int pixel3d = Integer.valueOf("3d3d3d", 16) - 16777216;
        int pixel3e = Integer.valueOf("3e3e3e", 16) - 16777216;
        int pixel38 = Integer.valueOf("383838", 16) - 16777216;
        int pixel2e = Integer.valueOf("2e2e2e", 16) - 16777216;
        int pixel35 = Integer.valueOf("353535", 16) - 16777216;
        int pixel3b = Integer.valueOf("3b3b3b", 16) - 16777216;
        int pixel32 = Integer.valueOf("323232", 16) - 16777216;

        try {
            bi = ImageIO.read(file);
            int width = bi.getWidth();
            int height = bi.getHeight();
            int minx = bi.getMinX();
            int miny = bi.getMinY();
            ByteArrayOutputStream outputStream = null;
//            int pixel1=Integer.valueOf(color,16);//转换成10进制颜色
//            int pixel2=Integer.valueOf(color1,16);//转换成10进制颜色

            int srcPixel = srcColor.getRGB();//转换成10进制颜色
            int targetPixel = targetColor.getRGB();//转换成10进制颜色

            bi1 = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR);//新建一个BufferedImage 防止某些PNG图片无法修改
            Graphics2D graphics = (Graphics2D) bi1.getGraphics();
            graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

            for (int i = minx; i < width; i++) {  //循环每个像素 然后修改
                for (int j = miny; j < height; j++) {
                    int pixel = bi.getRGB(i, j);
                    if (pixel == srcPixel || pixel == pixel0d || pixel == pixel3e
                            || pixel == pixel16 || pixel == pixel1c || pixel == pixel32
                            || pixel == pixel3d || pixel == pixel3d || pixel == pixel38
                            || pixel == pixel2e || pixel == pixel35 || pixel == pixel3b
                            || pixel == pixel22 || pixel == pixel2a || pixel == pixel26) {
//                        bi1.setRGB(i, j, pixel2-16777216);
                        bi1.setRGB(i, j, targetPixel);
                    } else {
                        bi1.setRGB(i, j, pixel);
                    }
                }
            }

            ImageIO.write(bi1, "jpeg", new File(targetPath));
        } catch (Exception ex) {
            System.out.println(ex.toString());
        }
        bi.flush();
        bi1.flush();
    }


    public static void yasuo(String path, Integer w1, Integer h1) {

        File image = new File(path);
        logger.info("------------file yasuo path=" + path);
        if (!image.exists()) {
            logger.info("------------file not exist for path=" + path);
            return;
        } else {
            logger.info("------------file exist for path=" + path);
        }
        if (path.toLowerCase().lastIndexOf(".png") > 0 ||
                path.toLowerCase().lastIndexOf(".jpg") > 0 ||
                path.toLowerCase().lastIndexOf(".jpeg") > 0) {
            logger.info("------------file is image" + path);
        } else {
            logger.info("------------file is not image");
            return;
        }

        try {
            BufferedImage originImage = ImageIO.read(new FileInputStream(path));
            int width = originImage.getWidth();
            int height = originImage.getHeight();

            if (width <= 750 && w1 == null) return;
            if (w1 != null && width <= w1) return;

            logger.info("------------originImage width=" + originImage.getWidth() + " height=" + originImage.getHeight());
            int wd1 = (w1 == null) ? 750 : w1;
            int hg1 = (h1 == null) ? wd1 * height / width : h1;
            logger.info("--------------------------w1=" + w1);
            if (w1 == null) {
                Thumbnails.of(path).size(wd1, hg1).toFile(path);
            } else {
                logger.info("------------w1 is not null height=" + height);
                logger.info("------------w1 is not null h1=" + h1);
                if (h1 != null && height <= h1) return;
                int i = 1;
                while (wd1 * i < width && hg1 * i < height) {
                    i++;
                }
                Thumbnails.of(path).sourceRegion(Positions.CENTER, wd1 * i, hg1 * i).size(wd1, hg1).keepAspectRatio(true)
                        .toFile(path);
            }

        } catch (Exception e) {
            logger.error("");
        }
    }

    public static void movebak(String path,String type) {

        File image = new File(path);
        logger.info("------------file movebak path=" + path);
        if (!image.exists()) {
            logger.info("------------file not exist for path=" + path);
            return;
        } else {
            logger.info("------------file exist for path=" + path);
        }

        if (path.toLowerCase().lastIndexOf(".png") > 0 ||
                path.toLowerCase().lastIndexOf(".jpg") > 0 ||
                path.toLowerCase().lastIndexOf(".jpeg") > 0) {
            logger.info("------------file is image" + path);
        } else {
            logger.info("------------file is not image");
            return;
        }
        if(path.indexOf("/"+type+"/")==-1)return;

        try {
            String imgbak = path.replace("/"+type+"/", "/"+type+"bak/");
            String cmd = "cp " + path + " " + imgbak;
            logger.info("----------------------------------------imgbak=" + imgbak);
            logger.info("----------------------------------------cmd=" + cmd);
            HttpUtil.checkDirectory(imgbak);

            try {
                Runtime.getRuntime().exec(cmd);
                logger.info("-------------------------------------------------------------movebak pic copy ok");
            } catch (Exception e) {
                logger.error("---------Runtime.getRuntime().exec error", e);
            }

        } catch (Exception e) {
            logger.error("");
        }
    }

    public static void restorebak(String path,String type) {

        try {

            String tar  = path.substring(0,path.indexOf("/"+type+"/"))+"/"+type+"/";
            logger.info("----------------------------------------tar=" + tar);

            String sour = tar.replace("/"+type+"/", "/"+type+"bak/*");
            logger.info("----------------------------------------sour=" + sour);

            String cmd = "mv " + sour + " " + tar;

            logger.info("----------------------------------------cmd=" + cmd);

            try {
                Runtime.getRuntime().exec(cmd);
                logger.info("-------------------------------------------------------------restorebak pic copy ok");
            } catch (Exception e) {
                logger.error("---------Runtime.getRuntime().exec error", e);
            }

        } catch (Exception e) {
            logger.error("");
        }
    }


}
